package com.jason.basicandroid.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpHandler {
	final int HTTP_GET = 0;
	final int HTTP_POST = 1;
	
	public String executeHttpGet(String url) {
		return executeHttp(HTTP_GET, url, null);
	}
	
	public String executeHttpPost(String url, List<NameValuePair> params) {
		return executeHttp(HTTP_POST, url, params);
	}
	
	private String executeHttp(int type, String url, List<NameValuePair> params) {
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer("");
		
		try {
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = null;
			if (HTTP_GET == type) {
				HttpGet request = new HttpGet(url);
				request.setURI(new URI(url));
				response = client.execute(request);
				
			} else if (HTTP_POST == type) {
				HttpPost request = new HttpPost(url);
				UrlEncodedFormEntity formEntry = new UrlEncodedFormEntity(params);
				request.setEntity(formEntry);
				response = client.execute(request);
			}
			
			in = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while((line = in.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return sb.toString();
	}
}
